import comSpSkeleton from "../../../../engines/components/comSpSkeleton";
import O1HD, { managers } from "../../../../engines/gameEngine";
import NormalLevelBase from "../../../../Game/Base/LevelBase";
import mainRoot from "../../../../Game/MainRoot";
import LevelLianXian_1Item from "./LevelLianXian_1Item";

const { ccclass, property } = cc._decorator;

export interface LianXianWayPoint {
    startNode: cc.Node,
    endNode: cc.Node,
    color: cc.Color
}

@ccclass
export default class LevelLianXian_1 extends NormalLevelBase {
    /** 当前选中的节点 */
    currentSelectNode: cc.Node = null;
    /** 之后选中的节点 */
    afterSelectNode: cc.Node = null;
    /** 当前成功答对的数量 */
    currentYesNum = 0;

    /** 控制画板相应（删除之前的) */
    cishuNum = 1;
    @property({tooltip:"倒计时"})
    /** 计时 */
    time: number = 60;
    /** 计时器--计时的 */
    timeDT = 0;
    /** 是否开始计时 */
    isStartTime: boolean = false;
    isPlaySound: boolean = false;

    errorSubTimeNum: number = 5;

    /** 画布组件 */
    ctx1: cc.Graphics = null;

    /** 计时Label */
    @property({ type: cc.Node, displayName: "计时Label" })
    timeLabel: cc.Node = null;
    /** */
    @property({ type: cc.Node, displayName: "倒计时文本" })
    countDownLabel: cc.Node = null;
    /** 画板--用于连续显示直线 */
    @property({ type: cc.Node, displayName: "画板-DrawingBoard" })
    DrawingBoard: cc.Node = null;
    /** 画板--用于存储 */
    @property({ type: cc.Node, displayName: "画板-DrawingBoard1" })
    DrawingBoard1: cc.Node = null;

    @property({ type: cc.String })
    sounds: string[] = [];

    @property({ type: cc.Node, displayName: "左边节点" })
    leftNode: cc.Node = null;
    @property({ type: cc.Node, displayName: "右边节点" })
    rightNode: cc.Node = null;

    @property({ displayName: '是否有倒计时' })
    isCountDown: boolean = true;

    @property()
    needCount: number = 8;

    @property()
    levelName: string = "";

    isPlaySoundNode: cc.Node = null;

    soundId: number = null;

    allPointPath: LianXianWayPoint[] = [];

    /** 连线成功之后还能不能继续点击item */
    @property()
    itemVaildIsClick: boolean = true;

    /**
     * 添加一个路径点
     */
    addOnePointPath(Point: LianXianWayPoint) {
        this.allPointPath.push(Point);
        // console.log(this.allPointPath,">>>>>>>>>>>>>>>>")
    }

    /**
     * 移除一个路径点
     */
    removeOnePointPath(point: LianXianWayPoint) {
        if (!point) return;
        let index = this.checkOnePointInIndex(point);
        // console.log(index,"index????")
        if (index > -1) {
            this.allPointPath.splice(index, 1);
        }
    }

    /**
     * 获取路径点在数组中的索引
     */
    checkOnePointInIndex(point: LianXianWayPoint) {
        return this.allPointPath.findIndex((wayPoint: LianXianWayPoint) => {
            return point.startNode.uuid == wayPoint.startNode.uuid && point.endNode.uuid == wayPoint.endNode.uuid;
        });
    }

    /**
     * 重绘所有路径点
     */
    redrawAllPointPath() {
        let graphics = this.DrawingBoard1.getComponent(cc.Graphics);
        graphics.clear();
        for (let i = 0; i < this.allPointPath.length; i++) {
            let pointPath = this.allPointPath[i];
            graphics.strokeColor = pointPath.color;
            let startVec = pointPath.startNode.getComponent(LevelLianXian_1Item).getNodePos(pointPath.startNode);
            let endVec = pointPath.startNode.getComponent(LevelLianXian_1Item).getNodePos(pointPath.endNode);
            graphics.moveTo(startVec.x, startVec.y);
            graphics.lineTo(endVec.x, endVec.y);
            graphics.stroke();
        }
    }

    onLoad() {
        super.onLoad();
        O1HD.getManagers().soundMgr.loadSoundBundle(this.levelName);
    }

    start() {
        super.start();
        this.init();
    }

    init() {
        this.timeLabel.getComponent(cc.Label).string = "" + this.time;
        this.ctx1 = this.DrawingBoard.getComponent(cc.Graphics);
        this.currentSelectNode = null;
        this.afterSelectNode = null;
        this.timeLabel.active = this.isCountDown;
        this.countDownLabel.active = this.isCountDown;
    }

    pauseGame(): void {
        this.isStartTime = false;
        if (this.isPlaySoundNode) {
            cc.audioEngine.pauseAllEffects();
            this.isPlaySoundNode.getComponent(LevelLianXian_1Item).isStartSoundTime = false;
            this.isPlaySoundNode.getChildByName("BoFang").getComponent(comSpSkeleton).timeScale = 0;
        }
    }
    resumeGame(): void {
        this.isStartTime = true;
        if (this.isPlaySoundNode) {
            cc.audioEngine.resumeAllEffects();
            this.isPlaySoundNode.getComponent(LevelLianXian_1Item).isStartSoundTime = true;
            this.isPlaySoundNode.getChildByName("BoFang").getComponent(comSpSkeleton).timeScale = 1;
        }
    }

    touchScene(e: cc.Event.EventTouch): void {
        let pos: cc.Vec2 = e.getLocation();
        pos = this.node.convertToNodeSpaceAR(pos);
        //    let node = cc.instantiate(this.md);
        //    mainRoot.UIRoot.addChild(node);
        //    node.setPosition(pos);
        //    node.getComponent(comSpSkeleton).playAnimation("animation").start(false).onComplete(1, () => {
        //        node.removeFromParent();
        //    });
    }

    stopSound() {
        if (this.soundId != null) {
            managers().soundMgr.stopSound(this.soundId);
            this.soundId = null;
            this.isPlaySoundNode.getComponent(LevelLianXian_1Item).init();
            this.isPlaySoundNode.getComponent(LevelLianXian_1Item).stopSoundAni();
            this.isPlaySoundNode = null;
        }
    }

    timeDaoJiShi: number = 5;

    update(dt) {
        if (!this.isCountDown) return;
        if (this.isStartTime) {
            if(this.allCheckDone)return
            this.timeDT += dt;
            if (this.timeDT >= 1) {
                this.time--;
                this.timeDT = 0;
                this.timeLabel.getComponent(cc.Label).string = "" + this.time;
                if (this.time <= this.timeDaoJiShi && !this.isPlaySoundNode) {
                    O1HD.getManagers().soundMgr.playSound("mainSound/daojishi");
                }
            }
            if (this.time <= 0) {
                this.isStartTime = false;
                this.isPlaySound = true;
                this.Lose(3);
            }
        }
    }

    //    Lose(time?: number) {
    //        if (this.hadEnd) { return; }
    //        this.hadEnd = true;
    //        let delayTime: number = 2;
    //        if (time) {
    //            delayTime = time;
    //        }
    //        managers().soundMgr.stopAllSound();
    //        this.timeLabel.getComponent(cc.Label).string ="0";
    //        managers().soundMgr.playSound('mainSound/zaojulose');
    //        // this.ShowObj("Xz_Cw", (node: cc.Node) => {
    //        //     if(position)
    //        //         node.setPosition(position);
    //        // });
    //        this.scheduleOnce(() => {
    //            managers().soundMgr.playSound('mainSound/inLevel');
    //            // let losePrams: ILosePagePrams = {
    //            //     mode: this.m_mode,
    //            //     loseText: this.levelInfo.loseText,
    //            //     tips: this.levelInfo.tips,
    //            //     index: this.levelInfo.level
    //            // };
    //            // mainRoot.UISystem.OpenPage(PAGE.LOSEPAGE, losePrams);
    //            mainRoot.LevelSystem.LoadLevel(mainRoot.LevelSystem.GetSignleLevelInfo(this.m_mode).bundleName, this.m_mode);
    //            mainRoot.UISystem.CloseAllPage();
    //        }, delayTime);
    //    }

    errorSubTime() {
        if (this.isCountDown) {
            let afterNode: cc.Node = this.afterSelectNode;
            let pos = afterNode.convertToWorldSpaceAR(cc.v2());
            let node = cc.instantiate(this.timeLabel);
            node.name = "lb";
            node.setParent(this.timeLabel.parent);
            node.setPosition(this.timeLabel.parent.convertToNodeSpaceAR(pos));
            let rotation: number = afterNode.getComponent(LevelLianXian_1Item).nodeRotation;
            let width: number = -afterNode.getChildByName("bg").width / 2;
            switch (rotation) {
                case 0: {
                    width = Math.abs(width)
                    break;
                }
            }
            node.x += width;
            this.time -= this.errorSubTimeNum;
            node.y += 25;
            node.getComponent(cc.Label).string = "-" + this.errorSubTimeNum;
            if (this.time <= 0) {
                this.timeLabel.getComponent(cc.Label).string = "0";
            }
            let speed: number = 1000;
            let time = node.getPosition().mag() / speed;
            // console.log(node.getPosition().mag(),speed,time,">>>>>>>>>>>>")
            cc.tween(node).by(0.5, { y: 20 }).call(() => {
                node.destroy();
                node.removeFromParent();
            }).start();
        }
    }

    canTouch:boolean = true;
    checkWin() {
        /** 判断当前答对的数量 达到目标时 调用胜利方法 */
        let leftNodes: cc.Node[] = this.leftNode.children;
        for (let i = 0; i < leftNodes.length; i++) {
            let n = leftNodes[i];
            if (!n.getComponent(LevelLianXian_1Item).currentWayPoint) {
                return;
            }
        }
        this.canTouch = false;
        this.Win(2);
        this.isStartTime = false;
        this.isPlaySound = true;

        if (this.currentYesNum >= this.needCount) {
        }
    }
    allCheckDone:boolean = false;
    isAllCheckDone(){
        let allDone = true
        let leftNodes: cc.Node[] = this.leftNode.children;
        for (let i = 0; i < leftNodes.length; i++) {
            let n = leftNodes[i];
            if (!n.getComponent(LevelLianXian_1Item).currentWayPoint) {
                allDone = false;
            }
        }

        this.allCheckDone = allDone;

    }

    binGoAni(num: number, ...args: any) {

    }
}
